<!-- 购物车简单案例 -->
<template>
    <div id='shopping'>
        <table width="600px" border="3px solid black">
            <thead>
                <tr>
                    <th class="td">名称</th>
                    <th class="td">数量</th>
                    <th class="td">单价</th>
                    <th class="td">操作</th>
                </tr>
            </thead>
            <tbody>
                <tr :key="item.name" v-for="(item) in commodityList">
                    <td class="td">{{ item.name }}</td>
                    <td class="td"> <button @click="addAndsub(item, false)">-</button> {{ item.num }} <button @click="addAndsub(item, true)">+</button> </td>
                    <td class="td">{{ item.price }}</td>
                    <td class="td"> <button @click="deleteFruit(item)">删除</button></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td class="td"></td>
                    <td class="td"></td>
                    <td class="td"></td>
                    <td class="td">总价：{{ totalPrice }}</td>
                </tr>
            </tfoot>
        </table>
    </div>
</template>

<script setup lang="ts">
    import { cp } from "fs";
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";

    interface fruit {name: string, price: number, num: number}
    // 定义水果数据
    const commodityList = reactive<fruit[]>([
        { name: 'apple', price: 30, num: 15 },
        { name: 'banana', price: 60, num: 5 },
        { name: 'pear', price: 10, num: 20 },
        { name: 'mango', price: 10, num: 30 },
    ])
    // 数量加减方法
    const addAndsub = (fruit: fruit, flag:boolean)=>{
        if (fruit.num == 0 && !flag) return ;
        if (flag) fruit.num++;
        else fruit.num--;
    }
    // 总价属性计算，使用computed
    const totalPrice = computed({
        get() {
            let allTotal = 0;
            for(let {price, num} of commodityList.values()) {
                allTotal += price * num;
            }
            return allTotal;
        },
        set() {}
    })
    // 删除水果
    const deleteFruit = (fruit:fruit)=>{
        for(let [index, {name}] of commodityList.entries()) {
            if (fruit.name == name) {
                commodityList.splice(index, 1);
                break;
            }
        }
    }
    
    onMounted(()=>{  })
</script>
<style scoped lang="less">
    .td {
        text-align: center;
    }
</style>